//
//  SEGDataPickerView.m
//  RACExample
//
//  Created by 山刘 on 2019/9/11.
//  Copyright © 2019 山刘. All rights reserved.
//
static CGFloat pickerHeight = 252;
static CGFloat headerHeight = 44;
#import "SEGDataPickerView.h"


@interface SEGPickerHeaderView : UIView
@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, strong) UIButton *confirmButton;
@property (nonatomic, strong) UILabel *titleLabel;
@end
@implementation SEGPickerHeaderView
-(instancetype)initWithFrame:(CGRect)frame{
    if (self == [super initWithFrame:frame]) {
        self.backgroundColor = kColor_L4;
        [self addSubview:self.cancelButton];
        [self addSubview:self.titleLabel];
        [self addSubview:self.confirmButton];
    }
    return self;
}

-(void)layoutSubviews{
    [super layoutSubviews];
    [self.cancelButton sizeToFit];
    self.cancelButton.frame = CGRectMake(15, (CGRectGetHeight(self.bounds) - CGRectGetHeight(self.cancelButton.bounds))*0.5,
                                         CGRectGetWidth(self.cancelButton.bounds), CGRectGetHeight(self.cancelButton.bounds));
    
    [self.titleLabel sizeToFit];
    self.titleLabel.frame = CGRectMake((CGRectGetWidth(self.bounds) - CGRectGetWidth(self.titleLabel.bounds))*0.5,
                                       (CGRectGetHeight(self.bounds) - CGRectGetHeight(self.titleLabel.bounds))*0.5,
                                       CGRectGetWidth(self.titleLabel.bounds), CGRectGetHeight(self.titleLabel.bounds));
    
    [self.confirmButton sizeToFit];
    self.confirmButton.frame = CGRectMake(CGRectGetWidth(self.bounds) - CGRectGetWidth(self.confirmButton.bounds) - 15,
                                          (CGRectGetHeight(self.bounds) - CGRectGetHeight(self.confirmButton.bounds))*0.5,
                                          CGRectGetWidth(self.confirmButton.bounds), CGRectGetHeight(self.confirmButton.bounds));
}


-(UIButton *)cancelButton{
    if (!_cancelButton) {
        _cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancelButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [_cancelButton setTitleColor:kColor_1 forState:UIControlStateNormal];
        [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelButton addTarget:self action:@selector(cancelButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return  _cancelButton;
}

-(void)cancelButtonClick:(UIButton*)sender{
}

-(UIButton *)confirmButton{
    if (!_confirmButton) {
        _confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        
        _confirmButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [_confirmButton setTitle:@"确定" forState:UIControlStateNormal];
        [_confirmButton setTitleColor:kColor_T forState:UIControlStateNormal];
        [_confirmButton addTarget:self action:@selector(confirmButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return  _confirmButton;
}

-(void)confirmButtonClick:(UIButton*)sender{
}

-(UILabel *)titleLabel{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.numberOfLines = 0;
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"" attributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFang SC" size: 16],NSForegroundColorAttributeName: kColor_1}];
        _titleLabel.attributedText = string;
    }
    return  _titleLabel;
}
@end



@interface SEGDataPickerView()<UIPickerViewDataSource,UIPickerViewDelegate,UIGestureRecognizerDelegate>
@property (nonatomic, strong)UIPickerView *pickerView;
@property (nonatomic, strong)SEGPickerHeaderView *headerView;

@property (nonatomic, strong)NSArray<NSArray<NSDictionary*>*> *dataSource;
@property (nonatomic, strong)NSMutableDictionary *selectedData;
@property (nonatomic, copy) pickerBlock block;
@property (nonatomic, copy) cancelBlock cancelBlock;
@end

@implementation SEGDataPickerView
+(void)showWithTitle:(NSString*)title data:(NSArray<NSArray<NSDictionary*>*>*)data pickerBlock:(nonnull pickerBlock)pickerBlock{
    SEGDataPickerView *view = [[SEGDataPickerView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), CGRectGetHeight([UIScreen mainScreen].bounds)) data:data];
    
    [view.headerView.titleLabel setText:title];
    view.block = pickerBlock;
    //[view.pickerView selectRow:2 inComponent:0 animated:YES];
    [[UIApplication sharedApplication].keyWindow addSubview:view];
    view.alpha = 0;
    [UIView animateWithDuration:0.2 animations:^{
        view.alpha = 1;
    }];
}

+(void)showWithTitle:(NSString*)title data:(NSArray<NSArray<NSDictionary*>*>*)data pickerBlock:(nonnull pickerBlock)pickerBlock cancelBlock:(nonnull cancelBlock)cancelBlock {
    SEGDataPickerView *view = [[SEGDataPickerView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), CGRectGetHeight([UIScreen mainScreen].bounds)) data:data];
    
    [view.headerView.titleLabel setText:title];
    view.block = pickerBlock;
    view.cancelBlock = cancelBlock;
    //[view.pickerView selectRow:2 inComponent:0 animated:YES];
    [[UIApplication sharedApplication].keyWindow addSubview:view];
    view.alpha = 0;
    [UIView animateWithDuration:0.2 animations:^{
        view.alpha = 1;
    }];
}



-(instancetype)initWithFrame:(CGRect)frame data:(NSArray<NSArray<NSDictionary*>*>*)data{
    if (self == [super initWithFrame:frame]) {
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
        [self addSubview:self.pickerView];
        [self addSubview:self.headerView];
        
        _dataSource = data;
        _selectedData = [NSMutableDictionary dictionary];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenView)];
        tap.delegate = self;
        //别忘了添加到testView上
        [self addGestureRecognizer:tap];
        [self addSubViews];
        [self setPickIndex];
    }
    return self;
}

-(void)addSubViews{
    [super layoutSubviews];
    self.pickerView.frame = CGRectMake(0, CGRectGetHeight(self.frame)-pickerHeight, CGRectGetWidth(self.frame), pickerHeight);
    self.headerView.frame = CGRectMake(0, CGRectGetMinY(self.pickerView.frame) - headerHeight, CGRectGetWidth(self.bounds), headerHeight);
}

- (void)setPickIndex {
    [self.dataSource enumerateObjectsUsingBlock:^(NSArray<NSDictionary *> * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        __block BOOL isSelect;
        [obj enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull objDict, NSUInteger idxDict, BOOL * _Nonnull stopDict) {
            if ([objDict.allKeys containsObject:@"select"]) {
                BOOL select = [[objDict valueForKey:@"select"] boolValue];
                if (select) {
                    isSelect = YES;
                    [self.pickerView selectRow:idxDict inComponent:idx animated:NO];
                }
            }
        }];
    }];
}

#pragma mark - UIPickerViewDataSource
//有几行
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return self.dataSource.count;
}
//行中有几列
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return self.dataSource[component].count;
}

#pragma mark - UIPickerViewDelegate
//列显示的数据
-(NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component{
    NSDictionary * data = self.dataSource[component][row];
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:[data valueForKey:@"desc"] attributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFang SC" size: 23],NSForegroundColorAttributeName: kColor_1}];
    return string;
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return 40;
}

-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    
    UIView *topSeparateLine = [pickerView.subviews objectAtIndex:1];
    UIView *bottomSeparateLine = pickerView.subviews.count >= 3?[pickerView.subviews objectAtIndex:2]:nil;
    if (topSeparateLine.frame.size.height < 1.0f &&
        bottomSeparateLine.frame.size.height < 1.0f) {
        topSeparateLine.backgroundColor = kColor_L2;
        bottomSeparateLine.backgroundColor = kColor_L2;
    } else {
        for (UIView *singleLine in pickerView.subviews) {
            if (singleLine.frame.size.height < 1.0f) {
                singleLine.backgroundColor = kColor_L2;
            }
        }
    }
    [pickerView.subviews objectAtIndex:0].backgroundColor = kColor_W2;
    
    // custom pickerView content label
    UILabel *pickerLabel = (UILabel *)view;
    
    // discussion: this is always nil, not Reusing, it's an iOS System bug.
    // reference: https://stackoverflow.com/questions/20635949/reusing-view-in-uipickerview-with-ios-7/21039321#21039321
    if (!pickerLabel) {
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.textAlignment = NSTextAlignmentCenter;
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        pickerLabel.backgroundColor = [UIColor clearColor];
    }
    pickerLabel.attributedText = [self pickerView:pickerView attributedTitleForRow:row forComponent:component];
    
    return pickerLabel;
}

- (UIPickerView *)pickerView {
    if (!_pickerView) {
        _pickerView = [[UIPickerView alloc] initWithFrame:CGRectZero];
        _pickerView.delegate = self;
        _pickerView.dataSource = self;
        _pickerView.backgroundColor = kColor_W;
        _pickerView.showsSelectionIndicator = YES;
        //[_pickerView setHidden:YES];
    }
    return _pickerView;
}

-(SEGPickerHeaderView *)headerView{
    if (!_headerView) {
        _headerView = [[SEGPickerHeaderView alloc] initWithFrame:CGRectZero];
        [_headerView.cancelButton addTarget:self action:@selector(cancelButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_headerView.confirmButton addTarget:self action:@selector(confirmButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _headerView;
}

-(void)cancelButtonClick:(UIButton*)sender{
    if (self.cancelBlock) {
        self.cancelBlock();
    }
    [self hiddenView];
}

-(void)confirmButtonClick:(UIButton*)sender{
    //最后点击确定 给一个选中的
    [self.dataSource enumerateObjectsUsingBlock:^(NSArray<NSDictionary *> * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.selectedData setObject:[obj objectAtIndex:[self.pickerView selectedRowInComponent:idx]] forKey:[NSString stringWithFormat:@"component_%zd",idx]];
    }];
    
    if (self.block) {
        self.block(self.selectedData);
    }
    [self hiddenView];
}

- (void)hiddenView {
    [UIView animateWithDuration:0.2 animations:^{
        self.alpha = 0;
    }completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

#pragma mark - gesture
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if (touch.view == self.pickerView || touch.view == self.headerView) {
        return NO;
    }
    return YES;
}


#pragma mark - traitCollectionDidChange
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    [super traitCollectionDidChange:previousTraitCollection];
}
@end
